import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, DatePicker, Dropdown, Form, Icon, Menu, Row, Select} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import UserCouponTable from '../../components/UserCouponTable';
import styles from './UserList.less';
import UserCouponModal from "../../components/UserCouponModal/index";


const {RangePicker} = DatePicker;

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');


@connect(state => ({
    coupon: state.coupon,
}))
@Form.create()
export default class Coupon extends PureComponent {
    state = {
        expandForm: false,
        selectedRows: [],
        formValues: {},
        type: 'email',
        user_id: 0
    };

    componentDidMount() {
        const {dispatch, match} = this.props;
        console.log(match.params);
        this.setState({
            user_id: match.params.id
        })
        dispatch({
            type: 'coupon/fetch',
            payload: {
                user_id: match.params.id
            }
        });
    }

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            page: pagination.current,
            size: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            console.log(sorter.order);
            // params.sorter = `${sorter.field}_${sorter.order}`;
            params.order = sorter.order;
            params.sorter = sorter.field;
        }

        dispatch({
            type: 'coupon/fetch',
            payload: params,
        });
    }

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'coupon/fetch',
            payload: {},
        });
    }

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    }

    handleMenuClick = (e) => {
        const {dispatch} = this.props;
        const {selectedRows} = this.state;

        if (!selectedRows) return;

        switch (e.key) {
            case 'remove':
                dispatch({
                    type: 'coupon/remove',
                    payload: {
                        items: selectedRows,
                    },
                    callback: () => {
                        this.setState({
                            selectedRows: [],
                        });
                        dispatch({
                            type: 'coupon/fetch',
                            payload: {
                                user_id: this.state.user_id
                            }
                        });
                    },
                });
                break;
            default:
                break;
        }
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    }

    handleSearch = (e) => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {};
            if (fieldsValue.keyword) {
                values.type = this.state.type;
                values.keyword = fieldsValue.keyword;
            }
            if (fieldsValue.created_at) {
                values.created_at = fieldsValue.created_at.map(item => item.format('YYYY-MM-DD HH:mm:ss'));
            }
            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'coupon/fetch',
                payload: values,
            });
        });
    }

    handleModalVisible = (flag) => {
        this.props.dispatch({
            type: 'coupon/changeVisible',
            payload: true,
            callback: () => {
                console.log('回调');
            },
        });
    }
    handleStatus = (status) => {
        // console.log(this.state.selectedRows);
        this.props.dispatch({
            type: 'coupon/status',
            payload: {
                status,
                items: this.state.selectedRows,
            },
            callback: () => {
                this.setState({
                    selectedRows: [],
                });

            },
        });
    }


    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;

        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="赠送时间">
                            {getFieldDecorator('created_at')(
                                <RangePicker/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                <span className={styles.submitButtons}>
                  <Button type="primary" htmlType="submit">查询</Button>
                  <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</Button>
                </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    handleAddSuccess = () => {
        const {dispatch, match} = this.props;

        this.setState({
            user_id: match.params.id
        })
        dispatch({
            type: 'coupon/fetch',
            payload: {
                user_id: match.params.id
            }
        });
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {
        const {coupon: {loading, data, confirmLoading, modalVisible}} = this.props;
        const {selectedRows} = this.state;
        const menu = (
            <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
                <Menu.Item key="remove">删除</Menu.Item>
            </Menu>
        );
        return (
            <PageHeaderLayout title="他的优惠券">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <Button icon="plus" type="primary"
                                    onClick={() => this.handleModalVisible(true)}>赠送优惠券</Button>
                            {
                                selectedRows.length > 0 && (
                                    <span>
                                  <Button onClick={() => this.handleStatus(2)}>作废
                                  </Button>
                                  <Dropdown overlay={menu}>
                                    <Button>
                        更多操作 <Icon type="down"/>
                                    </Button>
                                  </Dropdown>
                                </span>
                                )
                            }
                        </div>
                        <UserCouponTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={data}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <UserCouponModal onHandleAddSuccess={this.handleAddSuccess} user_id={this.state.user_id}/>
            </PageHeaderLayout>
        );
    }
}
